package com.opengw.controller;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.opengw.controller.processor.ProcessorFactory;
import com.opengw.exception.OpenGWException;

/**
 * Servlet implementation class BasicController
 */
public class BaseController extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public BaseController() {
        super();
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response);
	}
	
	private void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		ProcessorFactory factory = new ProcessorFactory();
		try{
			factory.getProcessor(request.getRequestURI()).processRequest(request, response);
		} catch (Exception e) {
			RequestDispatcher dispatcher = request.getRequestDispatcher(OpenGWException.DEFAULT_ERROR_PAGE);
			dispatcher.forward(request, response);
		}
	
	}

}
